import React, { useMemo, Suspense, lazy, memo, PropsWithChildren } from "react";
import { FilePreview_Mime } from "../../const";
import mime from "mime";
import { UploadFile } from "antd";
import { getFileTye } from "../../utils";
import ImagePreview from "./ImagePreview";

export interface WxFilePreviewProps extends PropsWithChildren {
  fileInfo: UploadFile<any> | string;
  filePreview?: (dom: React.LazyExoticComponent<React.ComponentType<any>>, file: UploadFile<any> | string) => React.ReactNode; //自定义预览
}
const FilePreview = ({ fileInfo, filePreview, ...otr }: WxFilePreviewProps) => {
  const fileName = typeof fileInfo == "object" ? fileInfo?.name : fileInfo;
  const fid = typeof fileInfo == "object" ? fileInfo?.uid : fileInfo;
  //只有值变化时才会重新加载组件
  const Render = useMemo<React.LazyExoticComponent<React.ComponentType<any>>>(
    () => lazy(() => FilePreview_Mime[(getFileTye(fileName || "image/png") as keyof typeof FilePreview_Mime) || "image"]),
    [fileName]
  );
  const Viewer = useMemo(() => {
    if (fileInfo instanceof Object) {
      //转换成BlobUrl
      return (
        <Suspense fallback={<ImagePreview></ImagePreview>}>
          {filePreview ? filePreview(Render, fileInfo) : React.createElement(Render, { src: fileInfo.originFileObj && URL.createObjectURL(fileInfo.originFileObj), ...otr })}
        </Suspense>
      );
    } else {
      return <Suspense fallback={<ImagePreview></ImagePreview>}>{filePreview ? filePreview(Render, fileInfo) : React.createElement(Render, { src: fileInfo, ...otr })}</Suspense>;
    }
  }, [fid]);

  return Viewer;
};

export default FilePreview;
